export default defineBackground(() => {
    browser.runtime.onInstalled.addListener(({ reason }) => {
        if (['install', 'update'].includes(reason)) {
            browser.contextMenus?.create({
                id: 'tts-sidePanel',
                title: 'tts-sidePanel',
                contexts: ['all']
            });
        }
    });
    browser.contextMenus?.onClicked.addListener((info, tab) => {
        if (info.menuItemId === 'tts-sidePanel') {
            // 配置sidePanel路径,使点击图标打开sidePanel生效
            browser.sidePanel.setOptions({ path: browser.runtime.getURL("/sidepanel.html") });
            browser.sidePanel.open({ windowId: tab.windowId });
            // 使点击图标打开sidePanel失效
            browser.sidePanel.setPanelBehavior({ openPanelOnActionClick: false }).catch((error) => console.error(error));
        }
    })
    const get = (url: string, params: any=null, headers={}) => {
        return new Promise((resolve, reject) => {
            // 使用 URLSearchParams 对象构建查询字符串
            if (params) {
                url += '?' + new URLSearchParams(params).toString()
            }
            fetch(url, { mode: 'cors', headers})
                .then(response => resolve(response.json()))
                .catch(error => {
                    // 处理错误
                    console.error(error);
                    reject(error)
                });
        })
    }
    const stream = (url: string, params: any=null, headers={}) => {
        return new Promise((resolve, reject) => {
            // 使用 URLSearchParams 对象构建查询字符串
            if (params) {
                url += '?' + new URLSearchParams(params).toString()
            }
            fetch(url, { mode: 'cors', headers})
                .then(response => response.blob())
                .then(data => {
                    resolve({data: new Blob([data]), type: data.type})
                })
                .catch(error => {
                    // 处理错误
                    console.error(error);
                    reject(error)
                });
        })
    }
    browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
        console.log(message)
        if (message.action === 'voices') {
            get(`https://t.leftsite.cn/voices`, message.params).then(data=>{
                return {voices: data}
            }).then(sendResponse)
            .catch(error => {
                sendResponse({error})
            })
            return true;
        }
        if (message.action === 'tts') {
            stream(`https://t.leftsite.cn/tts`, message.params).then(data=>{
                console.log(data)
                return {data}
            }).then(sendResponse)
            .catch(error => {
                sendResponse({error})
            })
            return true;
        }
    })
});
